package com.ruoyi.quartz.service.impl;

import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.code.BusinessBizCode;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.quartz.dao.SysJobLogDao;
import com.ruoyi.quartz.domain.SysJobLog;
import com.ruoyi.quartz.service.ISysJobLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 定时任务调度日志信息 服务层
 *
 * @author wintersnow
 * @since 1.0  2020-12-14
 */
@Service
public class SysJobLogServiceImpl implements ISysJobLogService {

    @Autowired
    private SysJobLogDao jobLogDao;

    /**
     * 获取quartz调度器日志的计划任务
     *
     * @param req 调度日志信息
     * @return 调度任务日志集合
     */
    @Override
    public Page<SysJobLog> selectJobLogList(SysJobLog req) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotNull(pageDomain.getPageNum()) && StringUtils.isNotNull(pageDomain.getPageSize())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        }
        Pageable pageable = PageRequest.of(pageDomain.getPageNum(), pageDomain.getPageSize(), Sort.Direction.DESC, pageDomain.getOrderBy());
        Specification<SysJobLog> example = new Specification<SysJobLog>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<SysJobLog> root,
                                         CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNoneBlank(req.getJobName())) {
                    Predicate pre = cb.like(root.get("jobName").as(String.class), "%" + req.getJobName() + "%");
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getInvokeTarget())) {
                    Predicate pre = cb.like(root.get("invokeTarget").as(String.class), "%" + req.getInvokeTarget() + "%");
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getJobGroup())) {
                    Predicate pre = cb.equal(root.get("jobGroup").as(String.class), req.getJobGroup());
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getStatus())) {
                    Predicate pre = cb.equal(root.get("status").as(String.class), req.getStatus());
                    list.add(pre);
                }
                if (null != req.getParams().get("beginTime")) {
                    Predicate pre = cb.greaterThanOrEqualTo(root.get("createTime").as(Date.class), (Date) req.getParams().get("beginTime"));
                    list.add(pre);
                }
                if (null != req.getParams().get("endTime")) {
                    Predicate pre = cb.lessThanOrEqualTo(root.get("createTime").as(Date.class), (Date) req.getParams().get("endTime"));
                    list.add(pre);
                }
                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        Page<SysJobLog> page = jobLogDao.findAll(example, pageable);
        return page;
    }

    /**
     * 通过调度任务日志ID查询调度信息
     *
     * @param jobLogId 调度任务日志ID
     * @return 调度任务日志对象信息
     */
    @Override
    public SysJobLog selectJobLogById(Long jobLogId) {
        SysJobLog sysJobLog = jobLogDao.findById(jobLogId).orElse(new SysJobLog());
        return sysJobLog;
    }

    /**
     * 新增任务日志
     *
     * @param jobLog 调度日志信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addJobLog(SysJobLog jobLog) {
        jobLogDao.save(jobLog);
    }

    /**
     * 批量删除调度日志信息
     *
     * @param logIds 需要删除的数据ID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteJobLogByIds(Long[] logIds) {
        return jobLogDao.deleteByJobLogIdIn(Arrays.asList(logIds));
    }

    /**
     * 删除任务日志
     *
     * @param jobId 调度日志ID
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteJobLogById(Long jobId) {
        jobLogDao.deleteById(jobId);
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 清空任务日志
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cleanJobLog() {
        jobLogDao.cleanJobLog();
    }
}
